//
//  GMVoiceRecoderView.m
//  Gmall
//
//  Created by yemeihua on 15/8/11.
//  Copyright (c) 2015年 Gmall. All rights reserved.
//

#import "GMVoiceRecordView.h"
#import <AVFoundation/AVFoundation.h>
#import "EMVoiceConverter.h"

@interface GMVoiceRecordView()<AVAudioRecorderDelegate>

@property (nonatomic,readonly) UIImageView *centerImageView;
@property (nonatomic,readonly) UIImageView *leftImageView;
@property (nonatomic,readonly) UIImageView *rightImageView;
@property (nonatomic,readonly) UILabel *tipLabel;
@property (nonatomic,readonly) AVAudioRecorder *recorder;
@property (nonatomic,readonly) NSDictionary *recordSetting;
@property (nonatomic,readonly) NSTimer *timer;
@property (nonatomic) NSUInteger peak;
@property (nonatomic,readonly) NSString *tempFilePath;




@end

@implementation GMVoiceRecordView

@synthesize recordSetting = _recordSetting;
@synthesize recorder = _recorder;
@synthesize tempFilePath = _tempFilePath;
@synthesize timer = _timer;
@synthesize duration = _duration;
@synthesize outputFilePath = _outputFilePath;

#pragma mark - 属性获取方法

- (NSDictionary *)recordSetting
{
    if (!_recordSetting)
    {
        _recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
                          [NSNumber numberWithFloat: 8000.0],AVSampleRateKey, //采样率
                          [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
                          [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,//采样位数 默认 16
                          [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,//通道的数目
                          nil];
    }
    
    return _recordSetting;
}

- (NSString *)tempFilePath
{
    if(!_tempFilePath)
    {
        _tempFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"record.wav"];
    }
    return _tempFilePath;
}

- (NSString *)outputFilePath
{
    if(!_outputFilePath)
    {
        _outputFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"record.amr"];
    }
    return _outputFilePath;
}

//语音录制对象
- (AVAudioRecorder *)recorder
{
    if(!_recorder)
    {
        NSURL *url = [NSURL fileURLWithPath:self.tempFilePath];
        _recorder = [[AVAudioRecorder alloc] initWithURL:url
                                               settings:self.recordSetting
                                                  error:nil];
        _recorder.meteringEnabled = YES;
        _recorder.delegate = self;
    }
    return _recorder;
}

- (void)setState:(GMVoiceRecoderViewState)state
{
    _state = state;
    switch (state)
    {
        case GMVoiceRecoderViewStateRecording:
            self.leftImageView.hidden = NO;
            self.rightImageView.hidden = NO;
            self.centerImageView.hidden = YES;
            self.leftImageView.image = [UIImage imageNamed:@"RecordingBkg"];
            [self  updateRightImage];
            self.tipLabel.backgroundColor = [UIColor clearColor];
            self.tipLabel.text = @"手指上滑，取消发送";
            self.tipLabel.font =[UIFont systemFontOfSize:14];
            break;
            
        case GMVoiceRecoderViewStateCanCancel:
            self.leftImageView.hidden = YES;
            self.rightImageView.hidden = YES;
            self.centerImageView.hidden = NO;
            self.tipLabel.backgroundColor = [UIColor yc_colorWithUInt:0xff0000 alpha:0.65];
            self.centerImageView.image = [UIImage imageNamed:@"RecordCancel"];
            self.tipLabel.text = @"松开手指，取消发送";
            self.tipLabel.font =[UIFont boldSystemFontOfSize:14];
            break;
        
        case GMVoiceRecoderViewStateWarn:
            self.leftImageView.hidden = YES;
            self.rightImageView.hidden = YES;
            self.centerImageView.hidden = NO;
            self.tipLabel.backgroundColor = [UIColor clearColor];
            self.centerImageView.image = [UIImage imageNamed:@"MessageTooShort"];
            self.tipLabel.font =[UIFont systemFontOfSize:14];
            self.tipLabel.text = @"说话时间太短";
            break;
            
        default:
            break;
    }
}

#pragma mark - 视图生命周期

- (instancetype)initWithFrame:(CGRect)frame
{
    frame = CGRectMake(0, 0, 150, 150);
    if(self = [super initWithFrame:frame])
    {
        self.layer.cornerRadius = 8.0;
        self.layer.masksToBounds = YES;
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.55];
        
        _centerImageView = [[UIImageView alloc] init];
        _centerImageView.hidden = YES;
        [self addSubview:self.centerImageView];
        
        [self.centerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self);
            make.top.equalTo(@20);
        }];
        
        _leftImageView = [[UIImageView alloc] init];
        [self addSubview:self.leftImageView];
        
        [self.leftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@30);
            make.top.equalTo(@10);
        }];
        
        _rightImageView = [[UIImageView alloc] init];
        [self addSubview:self.rightImageView];

        [self.rightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.leftImageView.mas_right);
            make.top.equalTo(@10);
        }];
        
        _tipLabel = [[UILabel alloc] init];
        _tipLabel.text = @"手指上滑，取消发送";
        _tipLabel.textAlignment = NSTextAlignmentCenter;
        _tipLabel.textColor = [UIColor whiteColor];
        _tipLabel.font =[UIFont systemFontOfSize:14];
        _tipLabel.layer.cornerRadius = 4;
        _tipLabel.layer.masksToBounds = YES;
        
        [self addSubview:self.tipLabel];
        
        [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(8);
            make.right.equalTo(self).offset(-8);
            make.bottom.equalTo(self).offset(-8);
            make.height.equalTo(@25);
        }];
    }
    return self;
}

#pragma mark - 自定义方法

- (void)startRecodeInView:(UIView *)view
{
    [self stop];
    self.state = GMVoiceRecoderViewStateRecording;
    
    self.center = CGPointMake(view.yc_width / 2.0, view.yc_width / 2.0 - 49);
    [view addSubview:self];
    
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:nil];
    
    BOOL result = [self.recorder prepareToRecord];
    
    _duration = 0;
    _peak = 1;
    
    //开始录制
    if(result)
    {
        [self.recorder record];
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:.03
                                                  target:self
                                                selector:@selector(didCallbackOfTimer:)
                                                userInfo:nil
                                                 repeats:YES];
    }
}

- (void)stop
{
    _peak = 1;
    
    [self.timer invalidate];
    _timer = nil;
    
    //停止语音录制
    [_recorder stop];
    
    if(self.recorder && self.duration > 1)
    {
        [[NSFileManager defaultManager] removeItemAtPath:self.outputFilePath error:NULL];
        [EMVoiceConverter wavToAmr:self.tempFilePath amrSavePath:self.outputFilePath];
        [[NSFileManager defaultManager] removeItemAtPath:self.tempFilePath error:NULL];
    }
    
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive:YES withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
    
    [self removeFromSuperview];
}


- (void)cancel
{
    [self stop];
    [[NSFileManager defaultManager] removeItemAtPath:self.tempFilePath error:NULL];
}

- (void)didCallbackOfTimer:(NSTimer *)timer
{
    @autoreleasepool
    {
        if(![NSThread isMainThread])
        {
            [self performSelectorOnMainThread:_cmd
                                   withObject:nil
                                waitUntilDone:YES];
            return;
        }
        
        if(!self.recorder.recording)
        {
            [self.timer invalidate];
            _timer = nil;
            return;
        }
        
        _duration = self.recorder.currentTime;
        
        [self.recorder updateMeters];
        _peak = 8 * pow(10, (0.025 * [self.recorder averagePowerForChannel:0]));
        [self updateRightImage];
    }
}

- (void)updateRightImage
{
    NSString *imageName = [NSString stringWithFormat:@"RecordingSignal00%ld",(unsigned long)self.peak];
    UIImage *image = [UIImage imageNamed:imageName];
    self.rightImageView.image = image;
}

#pragma mark - AVAudioRecorder delegate

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
    _duration = self.recorder.currentTime;
}

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error
{
    [self cancel];
}

@end
